#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2018/12/19 13:25
@desc
"""

import re


def parser_list(str_list):
    """
    把字符串"[A,B,C,1,2,3]"转换为List
    :param str_list:
    :return: ['A','B','C',1,2,3]
    """
    list_list = str_list.replace('[', '').replace(']', '')
    return list_list.split(',')


def replace_by_lst(sql, params):
    """
    把sql中的？占位符替换为params的值，可以把加单引号的逻辑方在这里做
    :param sql:
    :param params:
    :return: 替换后的SQL
    """
    for p in params:
        sql = re.sub('\?', p, sql, 1)
    return sql


p = re.compile('Executing Statement:\s*(?P<SQL>(insert|delete|update).*TB_GIS_GRID_SHAPE.*)', re.I)
p2 = re.compile('Parameters:(?P<PARAM>(.*))', re.I)
with open(r"D:\iProject\myPython\com\teradata\file\tomcat7-stdout.2018-12-11.log", mode='r') as f:
    orgi_lines = [line for line in f]
    # if (p.search(line) or p2.search(line)):
    #     print(line.strip())

tf = open(r'D:\iProject\myPython\com\teradata\file\target.sql','w')

l = len(orgi_lines)
i = 0
while i < l:
    line = orgi_lines[i].strip()
    if p.search(line):
        t = p.search(line).groupdict()
        # print(t)
        next_line = orgi_lines[i+1]
        if p2.search(next_line):
            ps = p2.search(next_line).group(1)
            pl = parser_list(ps)
            # pl = list(ps)
            t['PARAM'] = pl

            # print(ps)
        print(t)
        text_sql = replace_by_lst(t['SQL'], t['PARAM'])
        # tf.write(str(t['PARAM']) + " ---> " + str(t['SQL'] + '\n'))
        tf.write(text_sql + '\n')
    i += 1

tf.close()
